import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
/**
 * 使用说明：
 * <app-check-item [options]="options" (optionChange)="optionChange($event)"></app-check-item>
 * showCount: boolean 指示count是否显示, 默认为false
 * options: 数组形式
 * [
 *      {label: '运行', value: 1, count: 187, checked: false} // count不为必选项
 * ]
 * optionChange(): item改变后的回调
 */
@Component({
    selector: 'app-check-item',
    templateUrl: './check-item.component.html',
    styleUrls: ['./check-item.component.styl']
})
export class CheckItemComponent implements OnInit {
    @Input() showCount: boolean;
    @Input() selectMode: any = 'multiple';
    @Input() options: Array<{
        value: string,
        label: string,
        count?: number, // 不必要参数
        checked: boolean
    }>;

    @Output() optionChange = new EventEmitter();
    @Input() outputOption = [];
    constructor() { }

    ngOnInit() {
    }
    /**
     * 设置输出值
     * @param item: 当前视图操作的选项
     */
    setParam(item: any) {
        item.checked = !item.checked;
        if (this.selectMode === 'multiple') {
            if (item.checked) {
                this.outputOption.push(item);
            } else {
                const index = this.outputOption.indexOf(item);
                if (index > -1) {
                    this.outputOption.splice(index, 1);
                }
            }
            console.log('app-check-item结果列表：' + this.outputOption);
            this.optionChange.emit(this.outputOption);
        } else if (this.selectMode === 'single') {
            this.outputOption = [];
            const index = this.options.indexOf(item);
            if (index > -1) {
                this.options.forEach((option, i) => {
                    if (index !== i) {
                        option.checked = false;
                    }
                });
            }
            if (item.checked) {
                this.outputOption.push(item);
            }
            this.optionChange.emit(this.outputOption);
        }



    }
}
